<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;
use Traits\DataTree;

/**
 * 菜单管理
 */
class PermissionController extends AdminController
{
	protected string $table = "permissions";

    protected string $model = "permission";

    use DataTree;

    #[NoReturn] public function init(): void
    {
        if (Request::input("title")) {
            $this->where[] = ['permission_name','like', '%'.Request::input("title").'%'];
        }
		if (Request::input("type")) {
            $this->where[] = ['type',Request::input("type")];
        }
        $this->routeWhiteLst = ['permission@shortcut','permission@shortcutmenu','permission@myshortcutmenu'];
        parent::init();
    }

    /**
     * 获取所有路由列表
     * @return void
     */
    #[NoReturn] function getAllAction(): void
    {
        try {
            $info = $this->user;
            if ($info) {
                $role_ids = [];
                $role = [];
                if ($info->role) {
                    $role_ids = $info->role->pluck("role_id")->toArray();
                    $role = RoleModel::query()->whereIn("id",$role_ids)->get()->pluck("identify")->toArray();
                }
				$all = PermissionModel::query()->selectRaw("id,parent_id")->get()->toArray();
                $permission_id = RoleHasPermissionModel::query()->whereIn("role_id",$role_ids)
                    ->get()->pluck("permission_id")->toArray();
				$parent_id = [];
				$all = array_format($all);
				foreach($permission_id as $vo) {
					$parent_id = array_merge($this->getAllParentIds($all, $vo),$parent_id);
				}
				$permission_id = array_values(array_unique(array_merge($permission_id,$parent_id)));
                $per = PermissionModel::query()
                    ->whereIn("id",  $permission_id)
                    ->where("type",1)
                    ->selectRaw("id,permission_name,parent_id,route,icon,permission_mark,component,redirect,keepalive,hidden,module")
                    ->orderBy("sort",'desc')
                    ->get()
                    ->toArray();
                foreach ($per as $key => $vo) {
                    $per[$key]['name'] = $vo['permission_mark'];
                    $per[$key]['path'] = $vo['route'];
                    $iconStr = $this->transformElementIcon($vo['icon']);
                    $per[$key]['meta'] = [
                        'title' => $vo['permission_name'],
                        'icon' => $iconStr,
                        'hidden' => (bool)$vo['hidden'],
                        'roles' => $info->role ? $role : [],
                        'keepAlive' => (bool)$vo['keepalive']
                    ];
                    unset($per[$key]['permission_name']);
                    unset($per[$key]['icon']);
                    unset($per[$key]['permission_mark']);
                    unset($per[$key]['route']);
                    unset($per[$key]['keepalive']);
                }
                $permissionList = $this->getTree($per,'parent_id');
                $this->apiSuccess($permissionList,'获取成功',20000);
            }else {
                $this->apiError("账号异常");
            }
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 获取所有父级数据ID
     * @需求：通过ID获取所有父级数据
     * @param  array $data 数据
     * @param  int $id 节点ID
     * @return array  $result 结果数组
     */
    protected function getAllParentIds(array $data, int $id): array
    {
        $result = array();
        if (isset($data[$id]['parent_id'])) {
            while (@$data[$id]['parent_id']) {
                $result[] = $data[$id]['parent_id'];
                $id = $data[$id]['parent_id'];
            }
        }
        return $result;
    }

    /**
     * 获取所有数据
     * @return void
     */
    #[NoReturn] public function getDataAction(): void
    {
        try {
            $user = UserModel::query()->with(["role"])->where("id",$this->member_id)->first()->toArray();
            $menu_ids = [];
            if ($user['role_id']!=1) {
                $role = RoleModel::query()->where("id", $user['role_id'])->first()->toArray();
                $menu_ids = explode(",",$role['menu_ids']);
            }
            $data = PermissionModel::query()
                ->where($this->where)
                ->when($menu_ids, function ($query) use ($menu_ids) {
                    $query->whereIn("id", $menu_ids);
                })
				->when(Request::input("type"), function ($query,$value){
                    $query->where("type", $value);
                })
				->when(Request::input("title"), function ($query,$value){
                    $query->where("permission_name",'like', '%'.$value.'%');
                })
                ->selectRaw("id,permission_name,parent_id,icon,route,permission_mark,sort,hidden,created_at,type,
                keepalive,hidden,module")
                ->orderBy("sort","desc")
                ->get()->toArray();
            foreach ($data as  $key=>$vo) {
                $data[$key]['icon'] = $this->transformElementIcon($vo['icon']);
            }
            $data = $this->getTree($data, 'parent_id');
            $this->apiSuccess($data,'获取成功',20000);
        }catch (Exception $exception) {
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * element ui 图标转element plus
     * @param string $icon
     * @return string
     */
    protected function transformElementIcon(string $icon): string
    {
        if (Request::input("type","element-plus")=="element-plus") {
            if (str_contains($icon, "el-icon")) {
                $_icon = str_replace(["el-icon-", 's-'], "", $icon);
                $iconArr = explode("-", $_icon);
                $iconStr = '';
                foreach ($iconArr as $vo) {
                    $iconStr .= ucfirst($vo);
                }
                $iconStr = "el-icon-" . $iconStr;
            }else{
                $iconStr = $icon;
            }
        }else{
            $iconStr = $icon;
        }
        return $iconStr;
    }

    /**
     * 获取所有1、2级菜单数据
     * @return void
     */
    #[NoReturn] public function getSelectDataAction(): void
    {
        $data = PermissionModel::query()
            ->where("type", 1)
            ->selectRaw("id,permission_name,parent_id,route,icon,module,permission_mark,component,
        redirect,keepalive,type,hidden,created_at,sort")
            ->get()->toArray();
        $data = $this->getTree($data, 'parent_id');
        $this->apiSuccess($data,'获取成功',20000);
    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        try {
            $params  = Request::all();
            $this->cleanCache();
            if (Request::input("id") !== null) {
                PermissionModel::query()->where("id",Request::input("id"))->update($params);
                $this->apiSuccess([],"更新成功",20000);
            }else {
                if ($params['parent_id']) {
                    $parent = PermissionModel::query()->where("id",$params['parent_id'])->first();
                    $params['module'] = $parent ? $parent['module']:"";
                    $params['component'] = $params['route']??"";
                }else {
                    $params['component'] = "Layout";
                }
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                $res =  PermissionModel::insertGetId($params);
                $info =  PermissionModel::query()->where('id',$res)->first();
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 获取所有快捷菜单
     * @return void
     */
    #[NoReturn] public function shortcutAction(): void
    {
        try {
            $info = $this->user;
            if ($info) {
                $role_ids = [];
                if ($info->role) {
                    $role_ids = $info->role->pluck("role_id")->toArray();
                }
                $permission_id = RoleHasPermissionModel::query()->whereIn("role_id",$role_ids)
                    ->get()->pluck("permission_id")->toArray();
                $per = PermissionModel::query()
                    ->whereIn("id",  $permission_id)
                    ->where("type",1)
                    ->selectRaw("id,permission_name as label,parent_id")
                    ->orderBy("sort",'desc')
                    ->get()
                    ->toArray();
                $permissionList = $this->getTree($per,'parent_id');
                $result = [];
                foreach ($permissionList as $vo) {
                    if ($vo['children']) {
                        $result = array_merge($result,$vo['children']);
                    }else {
                        $result = array_merge($result,$vo);
                    }
                }
                $data = [
                    'left_nav'=>[],
                    'right_nav'=>[],
                ];
                $shortcut = ShortcutMenuModel::query()
                    ->where("user_id",$this->member_id)
                    ->get()->pluck("menu_id")->toArray();
                foreach ($result as $vo) {
                    if (in_array($vo['id'],$shortcut)) {
                        $data['right_nav'][] = $vo['id'];
                    }
                    $data['left_nav'][] = [
                        'key'=>$vo['id'],
                        'label'=>$vo['label'],
                    ];
                }
                $this->apiSuccess($data,'获取成功',20000);
            }else {
                $this->apiError("账号异常");
            }
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 编辑快捷菜单
     * @return void
     */
    #[NoReturn] public function shortcutMenuAction(): void
    {
        DB::beginTransaction();
        try {
            ShortcutMenuModel::where("user_id",$this->member_id)->delete();
            $insert = [];
            foreach (Request::input("menu_id") as $vo) {
                $insert[] = [
                    'user_id'=>$this->member_id,
                    'menu_id'=>$vo,
                    'created_at'=>date("Y-m-d H:i:s"),
                ];
            }
            ShortcutMenuModel::insert($insert);
            DB::commit();
            $this->apiSuccess([],"保存成功",20000);
        } catch (Exception $e) {
            DB::rollBack();
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 获取我的快捷菜单
     * @return void
     */
    #[NoReturn] public function myShortcutMenuAction(): void
    {
        try {
            $menu_id = ShortcutMenuModel::query()->where("user_id",$this->member_id)->get()->pluck("menu_id")->toArray();
            if (!$menu_id) {
                $role_ids = $this->user->role->pluck("role_id")->toArray();
                $permission_id = RoleHasPermissionModel::query()->whereIn("role_id",$role_ids)->get()->pluck("permission_id")->toArray();
                $menu_id = PermissionModel::query()->whereIn("id",$permission_id)
                    ->where("type",1)
                    ->where("component","<>","Layout")
                    ->where("hidden",0)
                    ->get()->pluck("id")->toArray();
            }
            $class_name = ['blue','purple','red','yellow','green','sky-blue','deep-blue','e158a6','d6c1'];
            $data = PermissionModel::query()->whereIn("id",$menu_id)
                ->selectRaw("id,permission_name,route,icon")
                ->limit(8)
                ->get()->toArray();
            $i = 0;
            foreach ($data as $key=>$vo) {
                if ($i>count($class_name)) $i=0;
                $data[$key]['route'] = "#".$vo['route'];
                $data[$key]['class_name'] = $class_name[$i];
                $i++;
            }
            $this->apiSuccess($data,"保存成功",20000);
        } catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
